﻿using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace NDBGen
{
    public class ScriptedDataEntry
    {
        internal ScriptedDataEntry(String sourceFilePath, ScriptedDataColumn[] columns, String[] entries)
        {
            this.Values = entries.ToArray();

            var loadedValueDir = new FileInfo(sourceFilePath).Directory.FullName;
            for (var index = 0; index < this.Values.Length; index++)
            {
                var value = this.Values[index];
                if (value.StartsWith("<"))
                {
                    var file = new FileInfo(Path.Combine(loadedValueDir, value.TrimStart('<')));
                    if (file.Exists)
                    {
                        switch(file.Extension.ToUpper())
                        {
                            case ".HTM":
                            case ".SQL":
                            case ".TXT":
                            case ".XML":
                                this.Values[index] = File.ReadAllText(file.FullName); break;

                            default: this.Values[index] = "0x" + BitConverter.ToString(File.ReadAllBytes(file.FullName)).Replace("-", String.Empty); break;
                        }
                    }
                }
                else if (value.StartsWith("#"))
                {
                    var sourceColumnName = value.Trim('#');
                    var sourceColumn = columns.SingleOrDefault(c => c.Name == sourceColumnName);
                    if (sourceColumn == null) throw new InvalidDataException(String.Format("The column {0} was specified as the target of a hash value GUID, but it doesn't exist in the table.", sourceColumnName));
                    var sourceColumnIndex = Array.IndexOf(columns, sourceColumn);
                    var sourceValue = entries[sourceColumnIndex];
                    var md5 = MD5.Create();
                    var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(sourceValue));
                    this.Values[index] = new Guid(hash).ToString();
                }
            }
        }

        public String[] Values { get; set; }

        public static ScriptedDataEntry Parse(String sourceFilePath, ScriptedDataColumn[] columns, String line)
        {
            var linq =
                from entry in line.Split('|')
                select entry.Trim();
            return new ScriptedDataEntry(sourceFilePath, columns, linq.ToArray());
        }
    }
}